package com.kangjia.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.kangjia.api.report.Advice;
import com.kangjia.api.report.Age;
import com.kangjia.api.report.BasePage;
import com.kangjia.api.report.Copy;
import com.kangjia.api.report.Health;
import com.kangjia.api.report.HealthIndex;
import com.kangjia.api.report.HomePage;
import com.kangjia.api.report.Personal;
import com.kangjia.api.report.Product;
import com.kangjia.api.report.Sign;
import com.kangjia.api.report.SuggestPage;
import com.kangjia.model.m0.service.ProductService;

import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONArray;

@Slf4j
public class ParserReportService {

	private DocumentContext context;
	private ProductService productService;

	private String targetIds;

	public ParserReportService(String report, ProductService productService) {
		super();
		this.context = JsonPath.parse(report);
		this.productService = productService;
	}

	public String createSuggest() {
		StringBuilder info = new StringBuilder();
		info.append(getHealthSuggest());
		return info.toString();
	}

	public String createSuggestDetail() {
		StringBuilder info = new StringBuilder();
		info.append(getHealthSuggest());

		if (StringUtils.isNotBlank(targetIds)) {
			List<Advice> diets = getProm("diet", targetIds);
			int i = 1;
			info.append("膳食建议<br>");
			for (Advice diat : diets) {
				if (StringUtils.isNoneBlank(diat.getPersonalizedAdvice())
						&& !"无".equalsIgnoreCase(diat.getPersonalizedAdvice())) {
					info.append("(" + i++ + ")" + diat.getIndexName() + " "
							+ diat.getPersonalizedAdvice().replaceAll("根据您的检测结果，", "，") + "<br>");
				}
			}
			List<Advice> nutritions = getProm("nutrition", targetIds);
			info.append("营养建议<br>");
			i = 1;
			for (Advice diat : nutritions) {
				if (StringUtils.isNoneBlank(diat.getPersonalizedAdvice())
						&& !"无".equalsIgnoreCase(diat.getPersonalizedAdvice())) {
					info.append("(" + i++ + ")" + diat.getPersonalizedAdvice().replaceAll("根据您的检测结果，", "，") + "<br>");
				}
			}
			List<Advice> motions = getProm("motion", targetIds);
			info.append("运动和生活方式建议<br>");
			i = 1;
			for (Advice diat : motions) {
				if (StringUtils.isNoneBlank(diat.getPersonalizedAdvice())
						&& !"无".equalsIgnoreCase(diat.getPersonalizedAdvice())) {
					info.append("(" + i++ + ")" + diat.getPersonalizedAdvice().replaceAll("根据您的检测结果，", "，") + "<br>");
				}
			}
		}

		return info.toString();
	}

	/**
	 * 获取重度指标数据信息
	 * 
	 * @return
	 */
	public Map<String, String> getServer() {
		Map<String, String> maps = new HashMap<>();
		String key = "$..thirdItems[?(@.abnormalLevel>=2)]"; // 查询所有异常指标
		JSONArray jsonArray = context.read(key);
		if (jsonArray.isEmpty()) {
			return null;
		}
		List<HealthIndex> list = new ArrayList<>(); // 异常指标列表
		HealthIndex index = null;
		for (int i = 0; i < jsonArray.size(); i++) { // 生成指标
			Map<?, ?> map = (Map<?, ?>) jsonArray.get(i);
			index = createHealthIndex(map);
			index.setAbnormalLevel(getValueFromMap(map, "abnormalLevel"));
			index.setInspectStandard(getValueFromMap(map, "inspectStandard"));
			list.add(index);
		}
		Collections.sort(list, new Comparator<HealthIndex>() { // 排序,如果重度指标排在前面,中度异常按分数排序,
			public int compare(HealthIndex o1, HealthIndex o2) {
				Integer o1Lvl = Integer.parseInt(o1.getAbnormalLevel());
				Integer o2Lvl = Integer.parseInt(o2.getAbnormalLevel());
				Integer o1Score = Integer.parseInt(o1.getScore());
				Integer o2Score = Integer.parseInt(o2.getScore());
				if (o1Lvl >= 4 && o2Lvl >= 4) { // 两个指标都是重度异常,按分数值排序
					if (o1Score < o2Score) {
						return -1;
					} else {
						return 1;
					}
				} else if (o1Lvl >= 4 && o2Lvl < 4) { // 一个重度指标,一个非重度指标,重度指标排前面
					return -1;
				} else if (o1Lvl >= 3 && o2Lvl >= 3) { // 两个中度指标,按分数值排序
					if (o1Score < o2Score) {
						return -1;
					} else {
						return 1;
					}
				} else if (o1Lvl >= 3 && o2Lvl < 3) {
					return -1;
				} else if (o1Lvl >= 2 && o2Lvl >= 2) { // 两个中度指标,按分数值排序
					if (o1Score < o2Score) {
						return -1;
					} else {
						return 1;
					}
				} else if (o1Lvl >= 2 && o2Lvl < 2) {
					return -1;
				}
				return 0;
			}
		});
		StringBuilder str = new StringBuilder();
		StringBuilder str1 = new StringBuilder();
		if (list.size() > 3) {
			maps.put("len", "3");
		} else {
			maps.put("len", String.valueOf(list.size()));
		}
		int i = 0;
		for (HealthIndex healthIndex : list) {
			if (i == 0) {
				str.append(healthIndex.getName());
				str1.append(healthIndex.getResultThirdId());
			} else {
				str.append("、" + healthIndex.getName());
				str1.append("," + healthIndex.getResultThirdId());
			}
			i++;
			if (i == 3) {
				break;
			}
		}
		maps.put("str", str.toString());
		targetIds = str1.toString();
		return maps;
	}

	private String getHealthSuggest() {
		String name = getName();
		String nick = getNick();
		String ps = getPS();
		String age = getAge();
		String percentage = getPercentage();
		Map<String, String> strs = getServer();
		String abnormals = "0";
		String abnormalsSize = "";
		if (strs != null) {
			abnormals = strs.get("str"); // getAbnormals().replace("[", "").replace("]", "");
			abnormalsSize = strs.get("len"); // getAbnormalsSize();
		}
		String str = productService.getTemp("temp", "1");
		if (StringUtils.isNoneBlank(str)) {
			str = str.replace("#cname#", name);
			str = str.replace("#sex#", nick);
			str = str.replace("#healthStat#", ps);
			str =str.replace("#age#", age);
			str =str.replace("#percentage#", percentage);
			str = str.replace("#errorIndex#", abnormals);
			str = str.replace("#errorNum#", abnormalsSize);
		}
		return str;
	}

	public String getNick() {
		String sex = getSex();
		return sex.equals("0") ? "女士" : "先生";
	}

	public Copy getCopy() {
		Copy copy = new Copy();
		copy.setPersonal(personal());
		copy.setPercentage(getPercentage());
		copy.setPhysicalAge(getAge());
		copy.setPs(getPS());
		copy.setName(getName());
		copy.setSex(getSex());
		Map<String, String> strs = getServer();
		String abnormals = "0";
		String abnormalsSize = "";
		if (strs != null) {
			abnormals = strs.get("str"); // getAbnormals().replace("[", "").replace("]", "");
			abnormalsSize = strs.get("len"); // getAbnormalsSize();
		}
		copy.setAbnormals(abnormals);
		copy.setAbnormalsSize(abnormalsSize);
		get(copy);
		copy.setScore(getTotalScore());
		int s = get("4");
		if(s > 0) {			
			copy.setReminder("基于您身体的异常状况，建议您7日后再次检查");
		} else {
			s = get("3");
			if (s > 0) {
				copy.setReminder("基于您身体的异常状况，建议您15日后再次检查");
			} else {				
				copy.setReminder("");
			}
		}
		return copy;
	}

	/**
	 * 生成指标营养建议
	 * 
	 * @param resultFirstId
	 * @param resultSecondId
	 * @param resultThirdId
	 * @param keyword
	 * @return
	 */
	public void get(Copy copy) {
		copy.setDiat(getProm("diet", targetIds));
		copy.setNutrition(getProm("nutrition", targetIds));
		copy.setMotion(getProm("motion", targetIds));
	}

	public Sign queryKpi(String resultFirstId, String resultSecondId, String resultThirdId) {
		Sign sign = new Sign();
		sign.setPersonal(personal()); // 首页个人信息
		sign.setDetectionTime(getInspectDate()); // 检测时间
		sign.setScore(getTotalScore()); // 总分数
		sign.setPs(getPS());
		sign.setPhysicalAge(getAge());
		sign.setIndex(healthIndex(resultFirstId, resultSecondId, resultThirdId));
		List<Advice> advices = get(resultFirstId, resultSecondId, resultThirdId, "motion");
		Advice ad = new Advice();
		StringBuilder inf = new StringBuilder();
		for (Advice advice : advices) {
			if (StringUtils.isNotBlank(advice.getPersonalizedAdvice())
					&& !"无".equalsIgnoreCase(advice.getPersonalizedAdvice())) {
				inf.append(advice.getPersonalizedAdvice() + "<br>");
			}
		}
		ad.setPersonalizedAdvice(inf.toString());
		List<Advice> l = new ArrayList<Advice>();
		l.add(ad);
		sign.setMotion(l);
		sign.setDiat(get(resultFirstId, resultSecondId, resultThirdId, "diet"));
		sign.setNutrition(get(resultFirstId, resultSecondId, resultThirdId, "nutrition"));
		return sign;
	}

	/**
	 * 查询非正常指标建议
	 * 
	 * @param resultFirstId
	 * @param resultSecondId
	 * @param resultThirdId
	 * @param keyword
	 * @return
	 */
	public List<Advice> getProm(String keyword, String ids) {
		if (StringUtils.isBlank(ids)) {
			return new ArrayList<>();
		}
		String key = "$..thirdItems[?(@.resultThirdId in [" + ids + "])]";
		key = key + ".." + keyword + ".*";
		JSONArray jsonArray = context.read(key);
		Map<String, Advice> ms = new TreeMap<>();
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			Advice advice = createAdvice(maps);
			if (!ms.containsKey(advice.getIndexTypeId())) {
				ms.put(advice.getIndexTypeId(), advice);
				getProduct(maps, advice);
			} else if (ms.containsKey(advice.getIndexTypeId())) {
				Advice o = ms.get(advice.getIndexTypeId());
				if (Integer.parseInt(advice.getAbnormalLevel()) > Integer.parseInt(o.getAbnormalLevel())) { // 轻重程度大于原有覆盖
					ms.put(advice.getIndexTypeId(), advice);
					getProduct(maps, advice);
				}
			}
		}
		return new ArrayList<>(ms.values());
	}

	/**
	 * 查询非正常指标建议
	 * 
	 * @param resultFirstId
	 * @param resultSecondId
	 * @param resultThirdId
	 * @param keyword
	 * @return
	 */
	public List<Advice> getProm(String keyword, Integer max) {
		String key = "$..thirdItems[?(@.abnormalLevel>=" + max + ")]";
		key = key + ".." + keyword + ".*";
		JSONArray jsonArray = context.read(key);
		Map<String, Advice> ms = new TreeMap<>();
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			Advice advice = createAdvice(maps);
			if (!ms.containsKey(advice.getIndexTypeId())) {
				ms.put(advice.getIndexTypeId(), advice);
				getProduct(maps, advice);
			} else if (ms.containsKey(advice.getIndexTypeId())) {
				Advice o = ms.get(advice.getIndexTypeId());
				if (Integer.parseInt(advice.getAbnormalLevel()) > Integer.parseInt(o.getAbnormalLevel())) { // 轻重程度大于原有覆盖
					ms.put(advice.getIndexTypeId(), advice);
					getProduct(maps, advice);
				}
			}
		}
		return new ArrayList<>(ms.values());
	}

	/**
	 * 生成指标营养建议
	 * 
	 * @param resultFirstId
	 * @param resultSecondId
	 * @param resultThirdId
	 * @param keyword
	 * @return
	 */
	public List<Advice> get(String resultFirstId, String resultSecondId, String resultThirdId, String keyword) {
		String key = "$.healthIndex[?(@.resultFirstId==" + resultFirstId + ")]";
		if (StringUtils.isNotBlank(resultSecondId)) {
			key = "$..secondItems[?(@.resultSecondId==" + resultSecondId + ")]";
		}
		if (StringUtils.isNotBlank(resultThirdId)) {
			key = "$..thirdItems[?(@.resultThirdId==" + resultThirdId + ")]";
		}
		key = key + ".." + keyword + ".*";
		JSONArray jsonArray = context.read(key);
		Map<String, Advice> ms = new TreeMap<>();
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			Advice advice = createAdvice(maps);
			if (!ms.containsKey(advice.getIndexTypeId())) {
				ms.put(advice.getIndexTypeId(), advice);
			} else if (ms.containsKey(advice.getIndexTypeId())) {
				Advice o = ms.get(advice.getIndexTypeId());
				if (Integer.parseInt(advice.getAbnormalLevel()) > Integer.parseInt(o.getAbnormalLevel())) { // 轻重程度大于原有覆盖
					ms.put(advice.getIndexTypeId(), advice);
				}
			}
			getProduct(maps, advice);
		}
		return new ArrayList<>(ms.values());
	}

	public HealthIndex healthIndex(String resultFirstId, String resultSecondId, String resultThirdId) {
		String key = "$.healthIndex[?(@.resultFirstId==" + resultFirstId + ")]";
		if (StringUtils.isNotBlank(resultSecondId)) {
			key = "$..secondItems[?(@.resultSecondId==" + resultSecondId + ")]";
		}
		if (StringUtils.isNotBlank(resultThirdId)) {
			key = "$..thirdItems[?(@.resultThirdId==" + resultThirdId + ")]";
		}
		JSONArray jsonArray = context.read(key);
		HealthIndex index = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			index = createHealthIndex(maps);
			index.setAbnormalLevel(getValueFromMap(maps, "abnormalLevel"));
			index.setInspectStandard(getValueFromMap(maps, "inspectStandard"));
		}
		return index;
	}

	public SuggestPage getSuggest() {
		SuggestPage page = new SuggestPage();
		Map<String, String> strs = getServer();
		String abnormals = "0";
		String abnormalsSize = "";
		if (strs != null) {
			abnormals = strs.get("str"); // getAbnormals().replace("[", "").replace("]", "");
			abnormalsSize = strs.get("len"); // getAbnormalsSize();
		}
		page.setAbnormals(abnormals);
		page.setAbnormalsSize(abnormalsSize);

		page.setPercentage(getPercentage());
		page.setPhysiologicalAge(getAge());
		page.setPs(getPS());
		List<HealthIndex> diets = new ArrayList<>();
		List<HealthIndex> nutritions = new ArrayList<>();
		List<HealthIndex> motions = new ArrayList<>();
		getThird(diets, nutritions, motions);
		page.setMotions(motions);
		page.setNutritions(nutritions);
		page.setDiets(diets);
		return page;
	}

	/**
	 * 健康指数一级指标所有页
	 * 
	 * @return
	 */
	public HomePage getFirstFullPage(String resultFirstId) {
		HomePage page = new HomePage();
		page.setPersonal(personal()); // 首页个人信息
		page.setDetectionTime(getInspectDate()); // 检测时间
		page.setScore(getTotalScore()); // 总分数
		page.setHealthIndex(getFirst(resultFirstId, true, true, false, false)); // 健康指数
		page.setPs(getPS());
		page.setPhysicalAge(getAge());
		return page;
	}

	/**
	 * 健康状态页
	 * 
	 * @return
	 */
	public HomePage getHealthStatPage() {
		HomePage page = new HomePage();
		page.setPersonal(personal()); // 首页个人信息
		page.setDetectionTime(getInspectDate()); // 检测时间
		page.setScore(getTotalScore()); // 总分数
		page.setHealth(getHealth());
		page.setPs(getPS());
		page.setPhysicalAge(getAge());
		return page;
	}

	/**
	 * 健康指数页
	 * 
	 * @return
	 */
	public HomePage getFirstPage() {
		HomePage page = new HomePage();
		page.setPersonal(personal()); // 首页个人信息
		page.setDetectionTime(getInspectDate()); // 检测时间
		page.setScore(getTotalScore()); // 总分数
		page.setHealthIndex(getFirst(null, false, false, false, false)); // 健康指数
		page.setPs(getPS());
		page.setPhysicalAge(getAge());
		return page;
	}

	/**
	 * 首页获取健康指数
	 * 
	 * @return
	 */
	public HomePage getHomePage() {
		long s = System.currentTimeMillis();
		HomePage page = new HomePage();
		page.setPersonal(personal()); // 首页个人信息
		page.setDetectionTime(getInspectDate()); // 检测时间
		page.setScore(getTotalScore()); // 总分数
		page.setHealthAdvice(getHealthAdvice()); // 健康方案
		page.setHealth(getHealth()); // 健康状态
		page.setHealthIndex(getFirst(null, true, false, false, false)); // 健康指数
		page.setPs(getPS());
		page.setPhysicalAge(getAge());
		page.setAges(getAges());
		page.setPercentage(getPercentage());
		Copy copy = getCopy();
		page.setCopy(copy);
		page.setHealthAdvice(createSuggest());
		log.info("首页耗时={}", System.currentTimeMillis() - s);
		int size = get("4");
		if(size > 0) {			
			page.setReminder("基于您身体的异常状况，建议您7日后再次检查");
		} else {
			size = get("3");			
			if(size > 0) {			
				page.setReminder("基于您身体的异常状况，建议您7日后再次检查");
			} else {
				page.setReminder("");
			}
		}
		return page;
	}

	/**
	 * 客户信息页,健康建议页使用
	 * 
	 * @param resultFirstId
	 * @return
	 */
	public BasePage getBasePage() {
		long s = System.currentTimeMillis();
		BasePage page = new BasePage();
		page.setPs(getPS());
		page.setPersonal(personal()); // 个人信息
		page.setScore(getTotalScore()); // 总分数
		List<HealthIndex> diets = new ArrayList<>();
		List<HealthIndex> nutritions = new ArrayList<>();
		List<HealthIndex> motions = new ArrayList<>();
		getThird(diets, nutritions, motions);
		page.setMotions(motions);
		page.setNutritions(nutritions);
		page.setDiets(diets);
		log.info("客户信息页耗时={}", System.currentTimeMillis() - s);
		return page;
	}

	/**
	 * 查询最差的三级指标
	 * 
	 * @return
	 */
	public void getThird(List<HealthIndex> diets, List<HealthIndex> nutritions, List<HealthIndex> motions) {
		String key = "$..thirdItems[?(@.abnormalLevel>=2 && @.inspectStandard>1)]";
		JSONArray jsonArray = context.read(key);
		// 排序,只要三个
		jsonArray.sort(new Comparator<Object>() {
			public int compare(Object o1, Object o2) {
				Map<?, ?> o1m = (Map<?, ?>) o1;
				Map<?, ?> o2m = (Map<?, ?>) o2;
				Integer o1Lvl = Integer.parseInt(o1m.get("abnormalLevel").toString());
				Integer o2Lvl = Integer.parseInt(o2m.get("abnormalLevel").toString());
				Integer o1Score = Integer.parseInt(o1m.get("score").toString());
				Integer o2Score = Integer.parseInt(o2m.get("score").toString());
				if (o1Lvl >= 4 && o2Lvl >= 4) { // 两个指标都是重度异常,按分数值排序
					if (o1Score < o2Score) {
						return -1;
					} else {
						return 1;
					}
				} else if (o1Lvl >= 4 && o2Lvl < 4) { // 一个重度指标,一个非重度指标,重度指标排前面
					return -1;
				} else if (o1Lvl >= 3 && o2Lvl >= 3) { // 两个中度指标,按分数值排序
					if (o1Score < o2Score) {
						return -1;
					} else {
						return 1;
					}
				} else if (o1Lvl >= 3 && o2Lvl < 3) {
					return -1;
				} else if (o1Lvl >= 2 && o2Lvl >= 2) { // 两个中度指标,按分数值排序
					if (o1Score < o2Score) {
						return -1;
					} else {
						return 1;
					}
				} else if (o1Lvl >= 2 && o2Lvl < 2) {
					return -1;
				}
				return 0;
			}
		});

		HealthIndex index = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			index = createHealthIndex(maps); // 指标信息

			getAdvice(maps, "diet", index, false);
			getAdvice(maps, "nutrition", index, true);
			getAdvice(maps, "motion", index, false);

			if (index.getDiat() != null && index.getDiat().size() > 0) {
				diets.add(index);
			}
			if (index.getNutrition() != null && index.getNutrition().size() > 0) {
				nutritions.add(index);
			}
			if (index.getMotion() != null && index.getMotion().size() > 0) {
				motions.add(index);
			}
			if (i == 3) {
				break;
			}
		}
	}

	/**
	 * 查询健康指标建议信息
	 * 
	 * @param resultFirstId
	 * @param keyword
	 * @param value
	 * @return
	 */
	public List<HealthIndex> getIndexByHigh(String resultFirstId, String value) {
		List<HealthIndex> list = new ArrayList<>();
		String key = "$..thirdItems[?(@.abnormalLevel==" + value + ")]";
		if (StringUtils.isNoneBlank(resultFirstId)) {
			key = "$.healthIndex[?(@.resultFirstId==" + resultFirstId + ")]..thirdItems[?(@.abnormalLevel==" + value
					+ ")]";
		}
		JSONArray jsonArray = context.read(key);
		HealthIndex index = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			index = createHealthIndex(maps);
			index.setAbnormalLevel(getValueFromMap(maps, "abnormalLevel"));
			index.setInspectStandard(getValueFromMap(maps, "inspectStandard"));
			getAdvice(maps, "diet", index, true);
			getAdvice(maps, "nutrition", index, true);
			getAdvice(maps, "motion", index, true);
			list.add(index);
		}
		return list.size() > 0 ? list : null;
	}

	/**
	 * 获取报告身体状况
	 * 
	 * @return
	 */
	public List<Health> getHealth() {
		JSONArray jsonArray = context.read("$.healthStatus");
		List<Health> list = new ArrayList<>();
		Health index = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			index = createHealth(maps);
			index.setAbnormalLevel(getValueFromMap(maps, "abnormalLevel"));
			index.setAnalysisResults(getValueFromMap(maps, "analysisResults"));
			list.add(index);
		}
		return list;
	}

	/**
	 * 三级指标推荐商品
	 * 
	 * @param maps
	 * @param advice
	 */
	public void getProduct(Map<?, ?> maps, Advice advice) {
		JSONArray jsonArray = getJsonArray(maps, "product");
		if (jsonArray == null) {
			return;
		}
		List<Product> products = new ArrayList<>();
		Product product = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> mps = (Map<?, ?>) jsonArray.get(i);
			product = createProduct(mps);
			products.add(product);
		}
		if (products.size() > 0) {
			advice.setProducts(products);
		}
	}

	/**
	 * 三级指标建议指标
	 * 
	 * @param maps
	 * @param key
	 * @param index
	 */
	public void getAdvice(Map<?, ?> maps, String key, HealthIndex index, boolean isProduct) {
		JSONArray jsonArray = getJsonArray(maps, key);
		if (jsonArray == null) {
			return;
		}
		Advice advice = null;
		Map<String, Advice> mvs = new HashMap<>();
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> mps = (Map<?, ?>) jsonArray.get(i);
			advice = createAdvice(mps);
			String itid = advice.getIndexTypeId();
			Advice old = mvs.get(itid);
			if (old == null) {
				mvs.put(itid, advice);
				if (isProduct) {
					getProduct(mps, advice);
				}
			} else if (old != null
					&& Integer.parseInt(advice.getAbnormalLevel()) >= Integer.parseInt(old.getAbnormalLevel())) {
				mvs.put(itid, advice);
				if (isProduct) {
					getProduct(mps, advice);
				}
			}
		}
		switch (key) {
		case "diet":
			index.setDiat(new ArrayList<>(mvs.values()));
			break;
		case "nutrition":
			index.setNutrition(new ArrayList<>(mvs.values()));
			break;
		case "motion":
			index.setMotion(new ArrayList<>(mvs.values()));
			break;
		}
	}

	/**
	 * 获取异常三级指标数据信息
	 * 
	 * @param resultThirdId
	 * @param resultSecondId
	 * @return
	 */
	public List<HealthIndex> getThirdProm(boolean isAdvice, boolean isProduct) {
		String key = "$..thirdItems[?(@.abnormalLevel>1)]";
		List<HealthIndex> list = new ArrayList<>();
		JSONArray jsonArray = context.read(key);
		HealthIndex index = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			index = createHealthIndex(maps);
			index.setAbnormalLevel(getValueFromMap(maps, "abnormalLevel"));
			index.setInspectStandard(getValueFromMap(maps, "inspectStandard"));
			index.setSuggestContent(getValueFromMap(maps, "suggestContent"));
			index.setGuideContent(getValueFromMap(maps, "guideContent"));
			if (isAdvice) {
				getAdvice(maps, "diet", index, isProduct);
				getAdvice(maps, "nutrition", index, true);
				getAdvice(maps, "motion", index, isProduct);
			}
			list.add(index);
		}
		return list;
	}

	/**
	 * 获取一级指标下的二级指标下的三级指标数据信息
	 * 
	 * @param resultThirdId
	 * @param resultSecondId
	 * @return
	 */
	public List<HealthIndex> getThird(String resultThirdId, String resultSecondId, boolean isAdvice,
			boolean isProduct) {
		log.info("查询三级指标resultSecondId={}", resultSecondId);
		List<HealthIndex> list = new ArrayList<>();
		String key = "$..thirdItems[?(@.resultSecondId==" + resultSecondId + ")]";
		if (StringUtils.isNotBlank(resultThirdId)) {
			key = "$..thirdItems[?(@.resultSecondId==" + resultSecondId + " && @.resultThirdId==" + resultThirdId
					+ ")]";
		}
		JSONArray jsonArray = context.read(key);
		HealthIndex index = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			index = createHealthIndex(maps);
			index.setAbnormalLevel(getValueFromMap(maps, "abnormalLevel"));
			index.setInspectStandard(getValueFromMap(maps, "inspectStandard"));
			index.setSuggestContent(getValueFromMap(maps, "suggestContent"));
			index.setGuideContent(getValueFromMap(maps, "guideContent"));
			if (isAdvice) {
				getAdvice(maps, "diet", index, isProduct);
				getAdvice(maps, "nutrition", index, true);
				getAdvice(maps, "motion", index, isProduct);
			}
			list.add(index);
		}
		return list;
	}

	/**
	 * 获取第一级指标下的二级指标数据信息
	 * 
	 * @param resultSecondId
	 * @param resultFirstId
	 * @param isQueryThird
	 * @return
	 */
	public List<HealthIndex> getSecond(String resultSecondId, String resultFirstId, boolean isQueryThird,
			boolean isAdvice, boolean isProduct) {
		log.info("查询二级指标,resultFirstId={}", resultFirstId);
		List<HealthIndex> list = new ArrayList<>();
		String key = "$.healthIndex[*].secondItems.*";
		if (StringUtils.isNotBlank(resultFirstId)) {
			key = "$.healthIndex[*].secondItems[?(@.resultFirstId==" + resultFirstId + ")]";
		}
		if (StringUtils.isNoneBlank(resultSecondId)) {
			key = "$.healthIndex[*].secondItems[?(@.resultFirstId==" + resultFirstId + " && @.resultSecondId=="
					+ resultSecondId + ")]";
		}
		JSONArray jsonArray = context.read(key);
		HealthIndex index = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			index = createHealthIndex(maps);
			if (isQueryThird) {
				index.setChildren(getThird(null, index.getResultSecondId(), isAdvice, isProduct));
			}
			list.add(index);
		}
		return list;
	}

	/**
	 * 获取第一级健康指标数据信息
	 * 
	 * @param resultFirstId
	 *            一级指标ID
	 * @param isQuerySecond
	 * @param isQueryThird
	 * @return
	 */
	public List<HealthIndex> getFirst(String resultFirstId, boolean isQuerySecond, boolean isQueryThird,
			boolean isAdvice, boolean isProduct) {
		log.info("查询报告一级指标");
		List<HealthIndex> list = new ArrayList<>();
		String key = "$.healthIndex";
		if (StringUtils.isNotBlank(resultFirstId)) {
			key = "$.healthIndex[?(@.resultFirstId==" + resultFirstId + ")]";
		}
		JSONArray jsonArray = context.read(key);
		HealthIndex index = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			index = createHealthIndex(maps);
			if (isQuerySecond) {
				index.setChildren(getSecond(null, index.getResultFirstId(), isQueryThird, isAdvice, isProduct));
			}
			list.add(index);
		}
		return list;
	}

	/**
	 * 获取指标下的指标信息
	 * 
	 * @param resultFirstId
	 * @return
	 */
	public List<HealthIndex> getFirst(String resultFirstId) {
		List<HealthIndex> list = new ArrayList<>();
		log.info("查询报告一级指标");
		String key = "$.healthIndex[?(@.resultFirstId==" + resultFirstId + ")].secondItems.*";
		JSONArray jsonArray = context.read(key);
		HealthIndex index = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			index = createHealthIndex(maps);
			JSONArray thirdJsonArray = (JSONArray) maps.get("thirdItems");
			for (int k = 0; k < thirdJsonArray.size(); k++) {
				maps = (Map<?, ?>) thirdJsonArray.get(k);
				HealthIndex third = createHealthIndex(maps);
				index.add(third);
			}
			list.add(index);
		}
		return list;
	}

	/**
	 * 检测时间
	 * 
	 * @return
	 */
	public String getInspectDate() {
		return context.read("$.inspectDate");
	}

	/**
	 * 健康方案及建议
	 * 
	 * @return
	 */
	public String getHealthAdvice() {
		return context.read("$.healthAdvice");
	}

	/**
	 * 总分数
	 * 
	 * @return
	 */
	public String getTotalScore() {
		Object o = context.read("$.totalScore");
		return o != null ? o.toString() : null;
	}

	/**
	 * 性别
	 * 
	 * @return
	 */
	public String getSex() {
		Object o = context.read("$.sex");
		return o != null ? o.toString() : null;
	}

	/**
	 * 身体状况
	 * 
	 * @return
	 */
	public String getPS() {
		Object o = context.read("$.ps");
		return o != null ? o.toString() : null;
	}

	/**
	 * 身体状况
	 * 
	 * @return
	 */
	public String getAge() {
		Object o = context.read("$.age");
		return o != null ? o.toString() : null;
	}

	/**
	 * 比率
	 * 
	 * @return
	 */
	public String getPercentage() {
		Object o = context.read("$.percentage");
		return o != null ? o.toString() : null;
	}

	/**
	 * 异常指标数据
	 * 
	 * @return
	 */
	public String getName() {
		Object o = context.read("$.cname");
		return o != null ? o.toString() : null;
	}

	/**
	 * 异常指标数据
	 * 
	 * @return
	 */
	public String getAbnormalsSize() {
		Object o = context.read("$.abnormalsSize");
		return o != null ? o.toString() : null;
	}

	/**
	 * 异常数据
	 * 
	 * @return
	 */
	public String getAbnormals() {
		Object o = context.read("$.abnormals");
		return o != null ? o.toString() : null;
	}

	public List<Age> getAges() {
		List<Age> ages = new ArrayList<>();
		String key = "$.healthIndex[*]";
		JSONArray jsonArray = context.read(key);
		Age age = null;
		for (int i = 0; i < jsonArray.size(); i++) {
			Map<?, ?> maps = (Map<?, ?>) jsonArray.get(i);
			age = new Age();
			String a = getValueFromMap(maps, "age");
			if (StringUtils.isNotBlank(a)) {
				age.setIndex(getValueFromMap(maps, "targetName"));
				age.setAge(a);
				ages.add(age);
			}
		}
		return ages;
	}

	/**
	 * 获取用户基本信息
	 * 
	 * @return
	 */
	public Personal personal() {
		Personal personal = new Personal();
		personal.setUserId(getValue("uid"));
		personal.setBirth(getValue("birth"));
		personal.setHeadPortrait(getValue("imgUrl"));
		personal.setMobile(getValue("mobile"));
		personal.setNickname(getName());
		personal.setSex(getSex());
		return personal;
	}

	public String getValue(String key) {
		Object o = context.read("$." + key);
		return o != null ? o.toString() : null;
	}

	/**
	 * 计算分数等级范围
	 * 
	 * @param score
	 * @return
	 */
	public String scoreLvl(int score) {
		if (score >= 90) {
			return "优秀";
		} else if (score > 80 && score < 90) {
			return "良好";
		} else {
			return "差";
		}
	}

	/**
	 * 创建指标基础信息
	 * 
	 * @return
	 */
	private Health createHealth(Map<?, ?> maps) {
		Health index = new Health();
		index.setName(getValueFromMap(maps, "targetName")); // 指标名称
		index.setInspectExplain(getValueFromMap(maps, "inspectExplain")); // 指标解释
		index.setSuggestContent(getValueFromMap(maps, "suggestContent"));
		index.setGuideContent(getValueFromMap(maps, "guideContent"));
		return index;
	}

	/**
	 * 创建指标基础信息
	 * 
	 * @return
	 */
	private HealthIndex createHealthIndex(Map<?, ?> maps) {
		HealthIndex index = new HealthIndex();
		index.setResultFirstId(getValueFromMap(maps, "resultFirstId")); // 一级指标ID
		index.setTargetId(getValueFromMap(maps, "targetId")); // 指标ID
		index.setScore(getValueFromMap(maps, "score")); // 指标分数
		index.setName(getValueFromMap(maps, "targetName")); // 指标名称
		index.setInspectExplain(getValueFromMap(maps, "inspectExplain")); // 指标解释
		index.setResultSecondId(getValueFromMap(maps, "resultSecondId")); // 二级指标ID
		index.setResultThirdId(getValueFromMap(maps, "resultThirdId")); // 三级指标ID
		index.setAge(getValueFromMap(maps, "age")); // 生理年龄
		return index;
	}

	/**
	 * 创建建议指标信息
	 * 
	 * @param maps
	 * @return
	 */
	private Advice createAdvice(Map<?, ?> maps) {
		Advice advice = new Advice();
		advice.setIndexTypeId(getValueFromMap(maps, "indexTypeId"));
		advice.setIndexName(getValueFromMap(maps, "index"));
		advice.setPersonalizedAdvice(getValueFromMap(maps, "personality"));
		advice.setSimpleAdvice(getValueFromMap(maps, "proposal"));
		advice.setAbnormalLevel(getValueFromMap(maps, "abnormalLevel"));
		advice.setDescribe(getValueFromMap(maps, "describe"));
		return advice;
	}

	/**
	 * 创建商品信息
	 * 
	 * @param maps
	 * @return
	 */
	private Product createProduct(Map<?, ?> maps) {
		Product product = null;
		String relationId = getValueFromMap(maps, "relationId");
		String imgUrl = getValueFromMap(maps, "imgUrl");
		if (StringUtils.isNotBlank(imgUrl)) {
			product = new Product();
			product.setImgUrl(getValueFromMap(maps, "imgUrl"));
			product.setInfo(getValueFromMap(maps, "info"));
			product.setPrice(getValueFromMap(maps, "price"));
			product.setProductName(getValueFromMap(maps, "productName"));
			product.setUrl(getValueFromMap(maps, "url"));
		} else {
			if (StringUtils.isNotBlank(relationId)) { // 历史报告处理
				product = productService.getProduct(relationId);
				product.setInfo(getValueFromMap(maps, "info"));
			}
		}
		return product;
	}

	/**
	 * 从map中获取参数值
	 * 
	 * @param maps
	 * @param key
	 * @return
	 */
	private String getValueFromMap(Map<?, ?> maps, String key) {
		Object value = maps.get(key);
		if (value != null) {
			return value.toString();
		} else {
			return null;
		}
	}

	/**
	 * 获取jsonArray属性
	 * 
	 * @param maps
	 * @param key
	 * @return
	 */
	private JSONArray getJsonArray(Map<?, ?> maps, String key) {
		Object value = maps.get(key);
		if (value != null) {
			return (JSONArray) value;
		} else {
			return null;
		}
	}
	
	/**
	 * 重度,中度指标数量
	 * 
	 * @param max
	 * @return
	 */
	public Integer get(String max) {
		String key = "$..thirdItems[?(@.abnormalLevel==" + max + ")]";
		JSONArray jsonArray = context.read(key);
		if (jsonArray.isEmpty()) {
			return 0;
		} else {
			return jsonArray.size();
		}
	}

	/**
	 * 报告编号
	 * 
	 * @return
	 */
	public String getSn() {
		Object o = context.read("$._id");
		return o != null ? o.toString() : null;
	}
}
